package store

import (
	"encoding/binary"

	"github.com/boltdb/bolt"
	"github.com/sirupsen/logrus"
)

var FSM fsm

type fsm struct {
	db   *bolt.DB
	step uint64
	iter uint64
}

func (f *fsm) Reset() {
	f.setStep(0)
}

func (f *fsm) setStep(step uint64) {
	f.step = step
	f.db.Update(func(t *bolt.Tx) error {
		b, err := t.CreateBucketIfNotExists([]byte("config"))
		if err == nil {
			var bts = make([]byte, 8)
			binary.BigEndian.PutUint64(bts, f.step)
			return b.Put([]byte("fsm"), bts)
		}
		return err
	})
}

func (f *fsm) Check(fn func() error, force ...bool) {
	f.iter++
	logrus.Info("----------执行第", f.iter, "步---------")
	if f.iter > f.step {
		err := fn()
		if err != nil {
			logrus.Fatalf("第%d步出错:%s", f.iter, err)
		}
		f.setStep(f.step + 1)
	} else if len(force) > 0 && force[0] {
		err := fn()
		if err != nil {
			logrus.Fatalf("第%d步出错:%s", f.iter, err)
		}
	} else {
		logrus.Infof("跳过第%d步", f.iter)
	}
}
